#include "server.h"
Server::Server(QObject *parent,int port):QTcpServer(parent)
{
    listen(QHostAddress::Any,port);
}

void Server::updateClients(QString msg, int length)
{
    emit updateServer(msg, length); //(a)
    for (int i=0; i<tcpClientSocketList. count(); i++)
    {
        QTcpSocket *item= tcpClientSocketList.at(i);
        if (item->write(msg.toLatin1(), length) !=length)
        {
            continue;
        }
    }

}

void Server::slotDisconnected(int descriptor)
{
    for (int i=0; i<tcpClientSocketList. count(); i++)
    {
        QTcpSocket *item= tcpClientSocketList.at(i);
        if (item->socketDescriptor () == descriptor)
        {
            tcpClientSocketList.removeAt(i);
            return;
        }
    }
}

void Server::incomingConnection(qintptr handle)
{
    TcpClientSocket *tcpClientSocket=new TcpClientSocket(this);                              //(a)
    connect(tcpClientSocket,&TcpClientSocket::updateClients,this,&Server::updateClients);    //(b)
    connect(tcpClientSocket,&TcpClientSocket::disconnected,this,&Server::slotDisconnected);  //(c)
    tcpClientSocket->setSocketDescriptor(handle);                                  //(d)
    tcpClientSocketList.append(tcpClientSocket);                                             //(e)
}
